// product.js
// 产品分析看板核心交互与图表渲染脚本
// 主要功能：模态框穿透、图表渲染入口、静态数据结构示例
// 所有内容均有中文注释，便于理解和维护

// =====================
// 1. 图表实例管理（避免重复创建）
// =====================
const chartInstances = {};

// 销毁指定canvas的Chart实例
function destroyChart(canvasId) {
    if (chartInstances[canvasId]) {
        chartInstances[canvasId].destroy();
        delete chartInstances[canvasId];
    }
}

// 创建Chart实例并保存引用
function createChart(canvasId, config) {
    // 先销毁已存在的实例
    destroyChart(canvasId);
    // 创建新实例并保存
    chartInstances[canvasId] = new Chart(document.getElementById(canvasId), config);
    return chartInstances[canvasId];
}

// =====================
// 2. 模态框穿透查询逻辑
// =====================
const modal = document.getElementById('detailModal');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const closeModal = document.getElementById('closeModal');
const closeModalBtn = document.getElementById('closeModalBtn');

// 打开模态框，type为指标标识
window.showDetail = function (type) {
    modal.classList.remove('hidden');
    // 根据type填充不同内容
    renderModalContent(type);
};

closeModal.onclick = closeModalBtn.onclick = function () {
    modal.classList.add('hidden');
};

// =====================
// 3. 模态内容渲染（产品分析全覆盖）
// =====================
function renderModalContent(type) {
    let title = '';
    let html = '';
    switch (type) {
        // 产品研发分析
        case 'projectProgress':
            title = '研发项目进度完成率 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    研发项目进度完成率反映了研发项目的执行效率和质量，是衡量研发能力的重要指标。高完成率表明研发团队执行力强，项目管理规范。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">年度趋势</h4>
                        <canvas id="modalProjectProgressChart" height="120"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">项目类型分布</h4>
                        <canvas id="modalProjectTypeChart" height="120"></canvas>
                    </div>
                </div>
            `;
            setTimeout(() => {
                // 年度趋势曲线图
                createChart('modalProjectProgressChart', {
                    type: 'line',
                    data: {
                        labels: ['2019', '2020', '2021', '2022', '2023'],
                        datasets: [{
                            label: '进度完成率',
                            data: [82, 84, 86, 87, 87.5],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22,93,255,0.1)',
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: '#86909C' } },
                            y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' } }
                        }
                    }
                });
                // 项目类型分布图
                createChart('modalProjectTypeChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['基础研究', '应用开发', '技术改进', '产品升级'],
                        datasets: [{
                            data: [25, 35, 25, 15],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F']
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'investmentOutput':
            title = '研发投入产出比 - 趋势分析';
            html = `<canvas id="modalInvestmentOutputChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInvestmentOutputChart', '投入产出比', [2.8, 2.9, 3.0, 3.1, 3.2]), 100);
            break;
        case 'investmentOutputDetail':
            title = '研发投入产出比 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    研发投入产出比反映了研发项目的经济效益，通过对比投入成本与产出价值，评估研发项目的投资回报率。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">投入产出对比</h4>
                        <canvas id="modalInvestmentOutputDetailChart" height="200"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3">
                        <h4 class="text-md font-medium mb-2">投入产出比分析</h4>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>产品A：</span>
                                <span class="text-success">投入120万 → 产出360万 (1:3.0)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>产品B：</span>
                                <span class="text-success">投入180万 → 产出540万 (1:3.0)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>产品C：</span>
                                <span class="text-success">投入150万 → 产出450万 (1:3.0)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>产品D：</span>
                                <span class="text-success">投入200万 → 产出600万 (1:3.0)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>产品E：</span>
                                <span class="text-success">投入160万 → 产出480万 (1:3.0)</span>
                            </div>
                        </div>
                        <div class="mt-4 p-2 bg-green-50 rounded text-xs">
                            <strong>分析结论：</strong>所有产品的投入产出比均为1:3.0，表明研发投资回报率稳定且良好，研发效率较高。
                        </div>
                    </div>
                </div>
            `;
            setTimeout(() => {
                createChart('modalInvestmentOutputDetailChart', {
                    type: 'bar',
                    data: {
                        labels: ['产品A', '产品B', '产品C', '产品D', '产品E'],
                        datasets: [
                            {
                                label: '投入成本(万元)',
                                data: [120, 180, 150, 200, 160],
                                backgroundColor: '#FF7D00',
                                yAxisID: 'y'
                            },
                            {
                                label: '产出价值(万元)',
                                data: [360, 540, 450, 600, 480],
                                backgroundColor: '#00B42A',
                                yAxisID: 'y'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { position: 'bottom' },
                            title: {
                                display: true,
                                text: '研发投入产出比分析'
                            }
                        },
                        scales: {
                            x: {
                                title: {
                                    display: true,
                                    text: '产品名称'
                                }
                            },
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '金额(万元)'
                                }
                            }
                        }
                    }
                });
            }, 100);
            break;
        case 'newTechRatio':
            title = '新技术应用占比 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    新技术应用占比反映了企业的技术创新能力和技术更新速度，是衡量企业技术竞争力的重要指标。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">技术应用分布</h4>
                        <canvas id="modalNewTechRatioChart" height="200"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3">
                        <h4 class="text-md font-medium mb-2">技术应用分析</h4>
                        <div class="space-y-3 text-sm">
                            <div class="flex items-center space-x-2">
                                <div class="w-3 h-3 rounded-full bg-blue-500"></div>
                                <span>新技术应用：68.5%</span>
                            </div>
                            <div class="flex items-center space-x-2">
                                <div class="w-3 h-3 rounded-full bg-gray-400"></div>
                                <span>传统技术：31.5%</span>
                            </div>
                        </div>
                        <div class="mt-4 p-2 bg-blue-50 rounded text-xs">
                            <strong>分析结论：</strong>新技术应用占比达到68.5%，表明企业技术创新能力较强，技术更新速度较快，具备良好的技术竞争力。
                        </div>
                    </div>
                </div>
            `;
            setTimeout(() => {
                createChart('modalNewTechRatioChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['新技术应用', '传统技术'],
                        datasets: [{
                            data: [68.5, 31.5],
                            backgroundColor: ['#165DFF', '#86909C']
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'patentCount':
            title = '专利申请数量 - 趋势分析';
            html = `<canvas id="modalPatentCountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPatentCountChart', '专利申请数量', [120, 130, 140, 150, 156]), 100);
            break;
        // 产品生产分析
        case 'productionCompletion':
            title = '生产计划完成率 - 趋势分析';
            html = `<canvas id="modalProductionCompletionChart" height="300"></canvas>`;
            setTimeout(() => {
                const productionCompletionData = {
                    labels: ['产品A', '产品B', '产品C', '产品D', '产品E'],
                    actual: [1200, 980, 850, 1100, 920],
                    plan: [1000, 1000, 800, 1000, 900]
                };
                // 计算完成率
                const completionRate = productionCompletionData.actual.map((v, i) => ((v / productionCompletionData.plan[i]) * 100).toFixed(1));
                // 组合图表数据
                const comboData = {
                    labels: productionCompletionData.labels,
                    datasets: [
                        {
                            label: '实际产量',
                            data: productionCompletionData.actual,
                            backgroundColor: '#165DFF',
                            yAxisID: 'y',
                            type: 'bar',
                            order: 1
                        },
                        {
                            label: '计划产量',
                            data: productionCompletionData.plan,
                            backgroundColor: '#0FC6C2',
                            yAxisID: 'y',
                            type: 'bar',
                            order: 1
                        },
                        {
                            label: '完成率(%)',
                            data: completionRate,
                            borderColor: '#FF7D00',
                            backgroundColor: 'rgba(255,125,0,0.1)',
                            yAxisID: 'y1',
                            type: 'line',
                            fill: false,
                            tension: 0.4,
                            order: 2
                        }
                    ]
                };
                createChart('productionCompletionChart', {
                    type: 'bar',
                    data: comboData,
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { display: false },
                            title: {
                                display: true,
                                text: '生产计划完成率TOP5'
                            }
                        },
                        scales: {
                            x: {
                                title: {
                                    display: true,
                                    text: '产品名称'
                                }
                            },
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '产量(件)'
                                }
                            },
                            y1: {
                                position: 'right',
                                beginAtZero: true,
                                min: 0,
                                max: 140,
                                grid: { drawOnChartArea: false },
                                title: {
                                    display: true,
                                    text: '完成率(%)'
                                }
                            }
                        }
                    }
                });
                // 生成三项图例
                generateProductionComboLegend(comboData);
            }, 100);
            break;
        case 'equipmentUtilization':
            title = '生产设备利用率 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    生产设备利用率反映了生产设备的运行效率和产能发挥程度，是衡量生产效率的重要指标。
                </div>
                <canvas id="modalEquipmentUtilizationChart" height="300"></canvas>
            `;
            setTimeout(() => {
                const equipmentData = {
                    labels: ['类别1', '类别2', '类别3', '类别4', '类别5'],
                    data: [30, 25, 20, 15, 10],
                    colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
                };
                createChart('modalEquipmentUtilizationChart', {
                    type: 'pie',
                    data: {
                        labels: equipmentData.labels,
                        datasets: [{
                            data: equipmentData.data,
                            backgroundColor: equipmentData.colors
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: false } }
                    }
                });
                generateEquipmentUtilizationLegend(equipmentData);
            }, 100);
            break;
        case 'productionEfficiency':
            title = '生产效率指数 - 趋势分析';
            html = `<canvas id="modalProductionEfficiencyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalProductionEfficiencyChart', '生产效率指数', [82, 84, 86, 87, 88.5]), 100);
            break;
        case 'productionCost':
            title = '单位生产成本 - 趋势分析';
            html = `<canvas id="modalProductionCostChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalProductionCostChart', '单位生产成本', [1400, 1350, 1300, 1270, 1250]), 100);
            break;
        // 产品质量分析
        case 'productQualification':
            title = '产品合格率 - 趋势分析';
            html = `<canvas id="modalProductQualificationChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalProductQualificationChart', '产品合格率', [94, 95, 95.5, 96, 96.8]), 100);
            break;
        case 'defectRate':
            title = '产品缺陷率 - 趋势分析';
            html = `<canvas id="modalDefectRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDefectRateChart', '产品缺陷率', [6, 5, 4.5, 4, 3.2]), 100);
            break;
        case 'complaintRate':
            title = '质量问题投诉率 - 产品批次明细';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    展示各产品批次的质量问题投诉量及投诉率，便于定位质量风险批次。
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm border rounded">
                        <thead>
                            <tr class="bg-gray-50 border-b">
                                <th class="py-2 px-3 text-left">产品批次</th>
                                <th class="py-2 px-3 text-right">投诉量</th>
                                <th class="py-2 px-3 text-right">投诉率</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="border-b">
                                <td class="py-2 px-3">批次A202401</td>
                                <td class="py-2 px-3 text-right">12</td>
                                <td class="py-2 px-3 text-right">2.1%</td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">批次B202401</td>
                                <td class="py-2 px-3 text-right">8</td>
                                <td class="py-2 px-3 text-right">1.7%</td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">批次C202401</td>
                                <td class="py-2 px-3 text-right">5</td>
                                <td class="py-2 px-3 text-right">1.2%</td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">批次D202401</td>
                                <td class="py-2 px-3 text-right">3</td>
                                <td class="py-2 px-3 text-right">0.8%</td>
                            </tr>
                            <tr>
                                <td class="py-2 px-3">批次E202401</td>
                                <td class="py-2 px-3 text-right">1</td>
                                <td class="py-2 px-3 text-right">0.3%</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'qualityCost':
            title = '质量成本率 - 趋势分析';
            html = `<canvas id="modalQualityCostChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalQualityCostChart', '质量成本率', [3.2, 3.0, 2.8, 2.6, 2.5]), 100);
            break;
        // 产品市场分析
        case 'marketShare':
            title = '产品市场占有率 - 趋势分析';
            html = `<canvas id="modalMarketShareChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalMarketShareChart', '市场占有率', [15.2, 16.0, 16.8, 17.5, 18.5]), 100);
            break;
        case 'salesGrowth':
            title = '产品销售增长率 - 趋势分析';
            html = `<canvas id="modalSalesGrowthChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSalesGrowthChart', '销售增长率', [12.5, 13.2, 14.1, 14.8, 15.8]), 100);
            break;
        case 'customerRepurchase':
            title = '客户复购率 - 趋势分析';
            html = `<canvas id="modalCustomerRepurchaseChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalCustomerRepurchaseChart', '客户复购率', [65, 67, 69, 71, 72.5]), 100);
            break;
        case 'customerSatisfaction':
            title = '客户满意度 - 趋势分析';
            html = `<canvas id="modalCustomerSatisfactionChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalCustomerSatisfactionChart', '客户满意度', [4.2, 4.3, 4.4, 4.5, 4.6]), 100);
            break;
        // 保密合规分析
        case 'supplierCompliance':
            title = '供应商保密达标率 - 趋势分析';
            html = `<canvas id="modalSupplierComplianceChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSupplierComplianceChart', '保密达标率', [92, 93, 94, 95, 95.8]), 100);
            break;
        case 'employeeCompliance':
            title = '员工保密合规率 - 趋势分析';
            html = `<canvas id="modalEmployeeComplianceChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalEmployeeComplianceChart', '保密合规率', [96, 96.5, 97, 97.8, 98.2]), 100);
            break;
        case 'documentSecurity':
            title = '文档安全等级 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>安全等级说明</b><br>
                    A级：最高安全等级，适用于绝密级文档<br>
                    B级：高安全等级，适用于机密级文档<br>
                    C级：中安全等级，适用于秘密级文档
                </div>
                <canvas id="modalDocumentSecurityChart" height="300"></canvas>
            `;
            setTimeout(() => {
                createChart('modalDocumentSecurityChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['A级', 'B级', 'C级'],
                        datasets: [{
                            data: [60, 30, 10],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00']
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'auditPassRate':
            title = '保密审计通过率 - 趋势分析';
            html = `<canvas id="modalAuditPassRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalAuditPassRateChart', '审计通过率', [92, 93, 94, 95, 96.5]), 100);
            break;
        // 二级穿透查询
        case 'projectProgressDetail':
            title = '研发项目进度完成率TOP5 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    展示研发项目中进度完成率最高的前5个项目，对比实际进度与计划进度的差异，帮助识别项目执行效率和计划准确性。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">TOP5项目进度对比</h4>
                        <canvas id="modalProjectProgressDetailChart" height="200"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3">
                        <h4 class="text-md font-medium mb-2">项目完成情况分析</h4>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>项目A：</span>
                                <span class="text-success">实际95% vs 计划90% (+5%)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>项目B：</span>
                                <span class="text-success">实际92% vs 计划90% (+2%)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>项目C：</span>
                                <span class="text-success">实际88% vs 计划85% (+3%)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>项目D：</span>
                                <span class="text-warning">实际85% vs 计划90% (-5%)</span>
                            </div>
                            <div class="flex justify-between">
                                <span>项目E：</span>
                                <span class="text-warning">实际82% vs 计划85% (-3%)</span>
                            </div>
                        </div>
                        <div class="mt-4 p-2 bg-blue-50 rounded text-xs">
                            <strong>分析结论：</strong>TOP5项目中，前3个项目超额完成计划，后2个项目略有滞后，整体执行情况良好。
                        </div>
                    </div>
                </div>
            `;
            setTimeout(() => {
                createChart('modalProjectProgressDetailChart', {
                    type: 'bar',
                    data: {
                        labels: ['项目A', '项目B', '项目C', '项目D', '项目E'],
                        datasets: [
                            {
                                label: '实际进度',
                                data: [95, 92, 88, 85, 82],
                                backgroundColor: '#165DFF',
                                yAxisID: 'y'
                            },
                            {
                                label: '计划进度',
                                data: [90, 90, 85, 90, 85],
                                backgroundColor: '#0FC6C2',
                                yAxisID: 'y'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { position: 'bottom' },
                            title: {
                                display: true,
                                text: '研发项目进度完成率TOP5'
                            }
                        },
                        scales: {
                            x: {
                                title: {
                                    display: true,
                                    text: '项目名称'
                                }
                            },
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '进度(%)'
                                }
                            }
                        }
                    }
                });
            }, 100);
            break;
        case 'newTechDetail':
            title = '新技术应用占比 - 饼图分析';
            html = `<canvas id="modalNewTechDetailChart" height="300"></canvas>`;
            setTimeout(() => {
                createChart('modalNewTechDetailChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['人工智能', '物联网', '区块链', '云计算', '大数据', '其他'],
                        datasets: [{
                            data: [25, 20, 15, 18, 12, 10],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C', '#C9CDD4']
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'productionCompletionDetail':
            title = '生产计划完成情况 - 双轴柱状图';
            html = `<canvas id="modalProductionCompletionDetailChart" height="300"></canvas>`;
            setTimeout(() => {
                createChart('modalProductionCompletionDetailChart', {
                    type: 'bar',
                    data: {
                        labels: ['产品A', '产品B', '产品C', '产品D', '产品E'],
                        datasets: [
                            {
                                label: '实际产量',
                                data: [1200, 980, 850, 1100, 920],
                                backgroundColor: '#165DFF',
                                yAxisID: 'y'
                            },
                            {
                                label: '计划产量',
                                data: [1000, 1000, 800, 1000, 900],
                                backgroundColor: '#0FC6C2',
                                yAxisID: 'y'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } },
                        scales: {
                            y: { beginAtZero: true }
                        }
                    }
                });
            }, 100);
            break;
        case 'equipmentUtilizationDetail':
            title = '设备利用率分布 - 饼图分析';
            html = `<canvas id="modalEquipmentUtilizationDetailChart" height="300"></canvas>`;
            setTimeout(() => {
                createChart('modalEquipmentUtilizationDetailChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['类型1', '类型2', '类型3', '类型4', '类型5'],
                        datasets: [{
                            data: [95, 88, 82, 75, 68],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'qualificationTrend':
            title = '产品合格率趋势 - 折线图';
            html = `<canvas id="modalQualificationTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalQualificationTrendChart', '产品合格率', [94, 95, 95.5, 96, 96.8]), 100);
            break;
        case 'defectTop3':
            title = '缺陷类型TOP3 - 柱状图';
            html = `<canvas id="modalDefectTop3Chart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalDefectTop3Chart', ['外观缺陷', '功能缺陷', '性能缺陷'], [45, 32, 23]), 100);
            break;
        case 'marketShareDetail':
            title = '产品市场占有率 - 柱状图';
            html = `<canvas id="modalMarketShareDetailChart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalMarketShareDetailChart', ['产品A', '产品B', '产品C', '产品D', '产品E'], [25, 20, 18, 15, 12]), 100);
            break;
        case 'repurchaseDetail':
            title = '客户复购分析 - 组合图';
            html = `<canvas id="modalRepurchaseDetailChart" height="300"></canvas>`;
            setTimeout(() => {
                createChart('modalRepurchaseDetailChart', {
                    type: 'bar',
                    data: {
                        labels: ['客户A', '客户B', '客户C', '客户D', '客户E'],
                        datasets: [
                            {
                                label: '购买金额(万元)',
                                data: [120, 95, 85, 75, 65],
                                backgroundColor: '#165DFF',
                                yAxisID: 'y'
                            },
                            {
                                label: '购买数量',
                                data: [85, 78, 72, 68, 62],
                                borderColor: '#FF7D00',
                                backgroundColor: 'rgba(255, 125, 0, 0.2)',
                                type: 'line',
                                yAxisID: 'y1'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } },
                        scales: {
                            y: { beginAtZero: true, position: 'left' },
                            y1: { beginAtZero: true, position: 'right', grid: { drawOnChartArea: false } }
                        }
                    }
                });
            }, 100);
            break;
        case 'supplierComplianceDetail':
            title = '供应商保密达标情况 - 明细列表';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    展示各供应商的保密资质、证书及联系方式等信息，便于合规管理。
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm border rounded">
                        <thead>
                            <tr class="bg-gray-50 border-b">
                                <th class="py-2 px-3 text-left">供应商名称</th>
                                <th class="py-2 px-3 text-left">法人</th>
                                <th class="py-2 px-3 text-right">注册资本</th>
                                <th class="py-2 px-3 text-center">保密资质</th>
                                <th class="py-2 px-3 text-center">拥有证书</th>
                                <th class="py-2 px-3 text-left">联系人</th>
                                <th class="py-2 px-3 text-left">联系电话</th>
                                <th class="py-2 px-3 text-center">附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="border-b">
                                <td class="py-2 px-3">供应商A</td>
                                <td class="py-2 px-3">张三</td>
                                <td class="py-2 px-3 text-right">5000万</td>
                                <td class="py-2 px-3 text-center">有</td>
                                <td class="py-2 px-3 text-center">三级保密证书</td>
                                <td class="py-2 px-3">李四</td>
                                <td class="py-2 px-3">138****1234</td>
                                <td class="py-2 px-3 text-center"><a href="#" class="text-primary underline">下载</a></td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">供应商B</td>
                                <td class="py-2 px-3">王五</td>
                                <td class="py-2 px-3 text-right">8000万</td>
                                <td class="py-2 px-3 text-center">有</td>
                                <td class="py-2 px-3 text-center">二级保密证书</td>
                                <td class="py-2 px-3">赵六</td>
                                <td class="py-2 px-3">139****5678</td>
                                <td class="py-2 px-3 text-center"><a href="#" class="text-primary underline">下载</a></td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">供应商C</td>
                                <td class="py-2 px-3">李明</td>
                                <td class="py-2 px-3 text-right">3000万</td>
                                <td class="py-2 px-3 text-center">无</td>
                                <td class="py-2 px-3 text-center">—</td>
                                <td class="py-2 px-3">王敏</td>
                                <td class="py-2 px-3">137****8888</td>
                                <td class="py-2 px-3 text-center"><a href="#" class="text-primary underline">—</a></td>
                            </tr>
                            <tr class="border-b">
                                <td class="py-2 px-3">供应商D</td>
                                <td class="py-2 px-3">周强</td>
                                <td class="py-2 px-3 text-right">2000万</td>
                                <td class="py-2 px-3 text-center">有</td>
                                <td class="py-2 px-3 text-center">三级保密证书</td>
                                <td class="py-2 px-3">刘洋</td>
                                <td class="py-2 px-3">136****2222</td>
                                <td class="py-2 px-3 text-center"><a href="#" class="text-primary underline">下载</a></td>
                            </tr>
                            <tr>
                                <td class="py-2 px-3">供应商E</td>
                                <td class="py-2 px-3">孙伟</td>
                                <td class="py-2 px-3 text-right">10000万</td>
                                <td class="py-2 px-3 text-center">有</td>
                                <td class="py-2 px-3 text-center">一级保密证书</td>
                                <td class="py-2 px-3">陈刚</td>
                                <td class="py-2 px-3">135****9999</td>
                                <td class="py-2 px-3 text-center"><a href="#" class="text-primary underline">下载</a></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'securityRiskTop5':
            title = '保密风险TOP5 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>风险分析</b><br>
                    保密风险需要重点关注，及时制定风险应对方案。建议建立"一风险一策"应对机制，包括技术防护、人员管理、制度完善等措施。
                </div>
                <div class="bg-white rounded-lg p-4">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b border-gray-200">
                                <th class="py-2 text-left">风险类型</th>
                                <th class="py-2 text-center">风险等级</th>
                                <th class="py-2 text-center">影响范围</th>
                                <th class="py-2 text-center">应对措施</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">数据泄露风险</td>
                                <td class="py-2 text-center text-danger">高风险</td>
                                <td class="py-2 text-center">核心数据</td>
                                <td class="py-2 text-center">加强数据加密</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">人员流动风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">技术秘密</td>
                                <td class="py-2 text-center">完善保密协议</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">供应链风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">供应商信息</td>
                                <td class="py-2 text-center">加强供应商管理</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">系统安全风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">IT系统</td>
                                <td class="py-2 text-center">升级安全防护</td>
                            </tr>
                            <tr>
                                <td class="py-2">物理安全风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">办公场所</td>
                                <td class="py-2 text-center">加强门禁管理</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            `;
            break;
        default:
            title = '详细分析';
            html = '<div>暂无详细内容</div>';
    }
    modalTitle.innerText = title;
    modalContent.innerHTML = html;
}

// =====================
// 4. 图表渲染入口（Chart.js）
// =====================

// 生成新技术应用占比图例
function generateNewTechLegend(data) {
    const legendContainer = document.getElementById('newTechLegend');
    if (!legendContainer) return;

    legendContainer.innerHTML = '';

    data.labels.forEach((label, index) => {
        const legendItem = document.createElement('div');
        legendItem.className = 'flex items-center space-x-2';

        const colorBox = document.createElement('div');
        colorBox.className = 'w-3 h-3 rounded-full';
        colorBox.style.backgroundColor = data.colors[index];

        const labelText = document.createElement('span');
        labelText.className = 'text-gray-700';
        labelText.textContent = `${label} (${data.data[index]}%)`;

        legendItem.appendChild(colorBox);
        legendItem.appendChild(labelText);
        legendContainer.appendChild(legendItem);
    });
}

// 生成项目进度图例
function generateProjectProgressLegend(data) {
    const legendContainer = document.getElementById('projectProgressLegend');
    if (!legendContainer) return;

    legendContainer.innerHTML = '';

    data.datasets.forEach((dataset) => {
        const legendItem = document.createElement('div');
        legendItem.className = 'flex items-center space-x-2 mb-2';

        const colorBox = document.createElement('div');
        colorBox.className = 'w-3 h-3 rounded';
        colorBox.style.backgroundColor = dataset.backgroundColor;

        const labelText = document.createElement('span');
        labelText.className = 'text-gray-700 text-xs';
        labelText.textContent = dataset.label;

        legendItem.appendChild(colorBox);
        legendItem.appendChild(labelText);
        legendContainer.appendChild(legendItem);
    });
}

// 生成投入产出比图例
function generateInvestmentOutputLegend(data) {
    const legendContainer = document.getElementById('investmentOutputLegend');
    if (!legendContainer) return;

    legendContainer.innerHTML = '';

    data.datasets.forEach((dataset) => {
        const legendItem = document.createElement('div');
        legendItem.className = 'flex items-center space-x-2 mb-2';

        const colorBox = document.createElement('div');
        colorBox.className = 'w-3 h-3 rounded';
        colorBox.style.backgroundColor = dataset.backgroundColor;

        const labelText = document.createElement('span');
        labelText.className = 'text-gray-700 text-xs';
        labelText.textContent = dataset.label;

        legendItem.appendChild(colorBox);
        legendItem.appendChild(labelText);
        legendContainer.appendChild(legendItem);
    });
}

// 折线图示例
function renderLineChart(canvasId, label, data, labels) {
    createChart(canvasId, {
        type: 'line',
        data: {
            labels: labels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
                label: label,
                data: data,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22,93,255,0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } }
        }
    });
}

// 柱状图
function renderBarChart(canvasId, labels, data) {
    createChart(canvasId, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '数值',
                data: data,
                backgroundColor: '#165DFF',
            }]
        },
        options: { responsive: true }
    });
}

// 生成生产计划完成率组合图图例
function generateProductionComboLegend(data) {
    const legendContainer = document.getElementById('productionCompletionLegend');
    if (!legendContainer) return;
    legendContainer.innerHTML = '';
    data.datasets.forEach((dataset) => {
        const legendItem = document.createElement('div');
        legendItem.className = 'flex items-center space-x-2 mb-2';
        const colorBox = document.createElement('div');
        colorBox.className = 'w-3 h-3 rounded';
        colorBox.style.backgroundColor = dataset.backgroundColor || dataset.borderColor;
        const labelText = document.createElement('span');
        labelText.className = 'text-gray-700 text-xs';
        labelText.textContent = dataset.label;
        legendItem.appendChild(colorBox);
        legendItem.appendChild(labelText);
        legendContainer.appendChild(legendItem);
    });
}

// 生成生产设备利用率图例
function generateEquipmentUtilizationLegend(data) {
    const legendContainer = document.getElementById('equipmentUtilizationLegend');
    if (!legendContainer) return;
    legendContainer.innerHTML = '';
    data.labels.forEach((label, i) => {
        const legendItem = document.createElement('div');
        legendItem.className = 'flex items-center space-x-2';
        const colorBox = document.createElement('div');
        colorBox.className = 'w-3 h-3 rounded-full';
        colorBox.style.backgroundColor = data.colors[i];
        const labelText = document.createElement('span');
        labelText.className = 'text-gray-700';
        labelText.textContent = `${label} (${data.data[i]}%)`;
        legendItem.appendChild(colorBox);
        legendItem.appendChild(labelText);
        legendContainer.appendChild(legendItem);
    });
}

// =====================
// 5. 页面加载后可自动渲染首页主要图表
// =====================
window.onload = function () {
    // 清理所有现有的Chart实例，避免重复创建
    Object.keys(chartInstances).forEach(canvasId => {
        destroyChart(canvasId);
    });

    // 侧边栏切换功能
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const toggleSidebar = document.getElementById('toggleSidebar');
    if (sidebar && mainContent && toggleSidebar) {
        toggleSidebar.onclick = function () {
            // 切换侧边栏宽度
            sidebar.classList.toggle('w-64');
            sidebar.classList.toggle('w-16');
            // 切换主内容区左边距
            mainContent.classList.toggle('pl-64');
            mainContent.classList.toggle('pl-16');
            // 切换侧边栏内文字显示
            sidebar.classList.toggle('sidebar-collapsed');
        };
    }

    // 产品研发分析图表
    if (document.getElementById('projectProgressChart')) {
        const projectProgressData = {
            labels: ['项目A', '项目B', '项目C', '项目D', '项目E'],
            datasets: [
                {
                    label: '实际进度',
                    data: [95, 92, 88, 85, 82],
                    backgroundColor: '#165DFF'
                },
                {
                    label: '计划进度',
                    data: [90, 90, 85, 90, 85],
                    backgroundColor: '#0FC6C2'
                }
            ]
        };

        createChart('projectProgressChart', {
            type: 'bar',
            data: {
                labels: projectProgressData.labels,
                datasets: projectProgressData.datasets
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: false }, // 隐藏默认图例
                    title: {
                        display: true,
                        text: '研发项目进度完成率TOP5'
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '项目名称'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '进度(%)'
                        }
                    }
                }
            }
        });

        // 生成自定义图例
        generateProjectProgressLegend(projectProgressData);
    }
    if (document.getElementById('investmentOutputChart')) {
        const investmentOutputData = {
            labels: ['产品A', '产品B', '产品C', '产品D', '产品E'],
            datasets: [
                {
                    label: '投入成本(万元)',
                    data: [120, 180, 150, 200, 160],
                    backgroundColor: '#FF7D00'
                },
                {
                    label: '产出价值(万元)',
                    data: [360, 540, 450, 600, 480],
                    backgroundColor: '#00B42A'
                }
            ]
        };

        createChart('investmentOutputChart', {
            type: 'bar',
            data: {
                labels: investmentOutputData.labels,
                datasets: investmentOutputData.datasets
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: false }, // 隐藏默认图例
                    title: {
                        display: true,
                        text: '研发投入产出比分析'
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '产品名称'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '金额(万元)'
                        }
                    }
                }
            }
        });

        // 生成自定义图例
        generateInvestmentOutputLegend(investmentOutputData);
    }
    if (document.getElementById('newTechChart')) {
        const newTechData = {
            labels: ['新技术应用', '传统技术'],
            data: [68.5, 31.5],
            colors: ['#165DFF', '#86909C']
        };

        createChart('newTechChart', {
            type: 'doughnut',
            data: {
                labels: newTechData.labels,
                datasets: [{
                    data: newTechData.data,
                    backgroundColor: newTechData.colors
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: false } // 隐藏默认图例
                }
            }
        });

        // 生成自定义图例
        generateNewTechLegend(newTechData);
    }

    // 产品生产分析图表
    if (document.getElementById('productionCompletionChart')) {
        const productionCompletionData = {
            labels: ['产品A', '产品B', '产品C', '产品D', '产品E'],
            actual: [1200, 980, 850, 1100, 920],
            plan: [1000, 1000, 800, 1000, 900]
        };
        // 计算完成率
        const completionRate = productionCompletionData.actual.map((v, i) => ((v / productionCompletionData.plan[i]) * 100));
        // 排序索引（按完成率降序）
        const sortedIdx = completionRate.map((v, i) => i)
            .sort((a, b) => completionRate[b] - completionRate[a]);
        // 排序后的数据
        const sortedLabels = sortedIdx.map(i => productionCompletionData.labels[i]);
        const sortedActual = sortedIdx.map(i => productionCompletionData.actual[i]);
        const sortedPlan = sortedIdx.map(i => productionCompletionData.plan[i]);
        const sortedRate = sortedIdx.map(i => completionRate[i].toFixed(1));
        // 组合图表数据
        const comboData = {
            labels: sortedLabels,
            datasets: [
                {
                    label: '实际产量',
                    data: sortedActual,
                    backgroundColor: '#165DFF',
                    yAxisID: 'y',
                    type: 'bar',
                    order: 1
                },
                {
                    label: '计划产量',
                    data: sortedPlan,
                    backgroundColor: '#0FC6C2',
                    yAxisID: 'y',
                    type: 'bar',
                    order: 1
                },
                {
                    label: '完成率(%)',
                    data: sortedRate,
                    borderColor: '#FF7D00',
                    backgroundColor: 'rgba(255,125,0,0.1)',
                    yAxisID: 'y1',
                    type: 'line',
                    fill: false,
                    tension: 0.4,
                    order: 2
                }
            ]
        };
        createChart('productionCompletionChart', {
            type: 'bar',
            data: comboData,
            options: {
                responsive: true,
                plugins: {
                    legend: { display: false },
                    title: {
                        display: true,
                        text: '生产计划完成率TOP5'
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '产品名称'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '产量(件)'
                        }
                    },
                    y1: {
                        position: 'right',
                        beginAtZero: true,
                        min: 0,
                        max: 140,
                        grid: { drawOnChartArea: false },
                        title: {
                            display: true,
                            text: '完成率(%)'
                        }
                    }
                }
            }
        });
        // 生成三项图例
        generateProductionComboLegend(comboData);
    }
    if (document.getElementById('equipmentUtilizationChart')) {
        const equipmentData = {
            labels: ['类型1', '类型2', '类型3', '类型4', '类型5'],
            data: [30, 25, 20, 15, 10],
            colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
        };
        createChart('equipmentUtilizationChart', {
            type: 'pie',
            data: {
                labels: equipmentData.labels,
                datasets: [{
                    data: equipmentData.data,
                    backgroundColor: equipmentData.colors
                }]
            },
            options: {
                responsive: true,
                plugins: { legend: { display: false } }
            }
        });
        generateEquipmentUtilizationLegend(equipmentData);
    }

    // 产品质量分析图表
    if (document.getElementById('qualificationTrendChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const qualificationData = [94, 95, 95.5, 96, 96.8];
        renderLineChart('qualificationTrendChart', '产品合格率', qualificationData, years);
    }
    if (document.getElementById('defectTop3Chart')) {
        const labels = ['外观缺陷', '功能缺陷', '性能缺陷'];
        const data = [45, 32, 23];
        renderBarChart('defectTop3Chart', labels, data);
    }

    // 产品市场分析图表
    if (document.getElementById('marketShareChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const marketShareData = [15.2, 16.0, 16.8, 17.5, 18.5];
        renderLineChart('marketShareChart', '产品市场占有率', marketShareData, years);
    }
    if (document.getElementById('repurchaseChart')) {
        createChart('repurchaseChart', {
            type: 'bar',
            data: {
                labels: ['客户A', '客户B', '客户C', '客户D', '客户E'],
                datasets: [
                    {
                        label: '购买金额(万元)',
                        data: [120, 95, 85, 75, 65],
                        backgroundColor: '#165DFF',
                        yAxisID: 'y'
                    },
                    {
                        label: '购买数量',
                        data: [85, 78, 72, 68, 62],
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255, 125, 0, 0.2)',
                        type: 'line',
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: { legend: { position: 'bottom' } },
                scales: {
                    y: { beginAtZero: true, position: 'left' },
                    y1: { beginAtZero: true, position: 'right', grid: { drawOnChartArea: false } }
                }
            }
        });
    }

    // 保密合规分析图表
    if (document.getElementById('supplierComplianceChart')) {
        const labels = ['一级供应商', '二级供应商', '三级供应商', '四级供应商'];
        const data = [98, 95, 92, 88];
        renderBarChart('supplierComplianceChart', labels, data);
    }
}; 